﻿using Azure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model.Dto;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.ServiceBus.Services.Impl
{
    public class AppSystemService : BaseEFService<AppSystem>, IAppSystemService
    {
        Context db;
        public AppSystemService(Context context) : base(context)
        {
            db = context;
        }
        public async Task<List<AppSystemDto>> QueryPageAsync(AppSystemDto dto)
        {
            Expression<Func<AppSystemDto, bool>> expression = param => true;
            if (!string.IsNullOrEmpty(dto.Key))
            {
                expression = expression.And(a => a.CNName.Contains(dto.Key) || a.Code.Contains(dto.Key) || a.CNAbbr.Contains(dto.Key));
            }
            var linq = db.AppSystem
                .Select(a => new AppSystemDto
                {
                    Id = a.Id,
                    OrgId = a.OrgId,
                    Code = a.Code,
                    CNName = a.CNName,
                    CNAbbr = a.CNAbbr,
                    ENName = a.ENName,
                    ENAbbr = a.ENAbbr,
                    ThresholdValue = a.ThresholdValue,
                    CreateDate = a.CreateDate,
                    CreateUserId = a.CreateUserId,
                    UpdateDate = a.UpdateDate,
                    UpdateUserId = a.UpdateUserId,
                })
                .Where(expression);
            var result = new List<AppSystemDto>();
            if(dto.Pagination != null)
            {
                dto.Pagination.DataCount = linq.Count();
                result = await linq
                    .Skip((dto.Pagination.Page - 1) * dto.Pagination.PageSize)
                    .Take(dto.Pagination.PageSize)
                    .ToListAsync();
            }
            else
            {
                result = await linq.ToListAsync();
            }

            return result;
        }
    }
}
